package Controller;

import java.io.IOException;
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.logging.Level;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import util.DateUtil;

import exception.DAOSystemException;

import model.AppliedDataDTO;
import model.CompensationLeaveDTO;
import model.DetailDTO;
import model.HolidayCalendarDTO;
import bizlogic.CompensationLeaveManager1;
import bizlogic.HolidayCalendarManager;
import bizlogic.LeaveManager1;
import bizlogic.UserManager1;
import model.CalculateDTO;
/**
 * Servlet implementation class ProcessForLeave
 * --Hnin Phyo--
 */
@WebServlet({ "/ProcessForLeave", "/LeaveProcess" })
public class ProcessForLeave extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ProcessForLeave() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
				
		String status=request.getParameter("status").trim();
		String type=request.getParameter("type").trim();
		String userid=request.getParameter("userid").trim();
	    Date from=DateUtil.stringToDATE(request.getParameter("from"));
	    Date to=DateUtil.stringToDATE(request.getParameter("to"));
		if(status.equals("Approve") && !type.equalsIgnoreCase("Compensation Leave"))
		{			
			UserManager1 um=new UserManager1();
			CalculateDTO calculatedata=um.getData(userid,type);
			System.out.println(calculatedata.getFrom());
		    double day;

				try {
					day = calculate(calculatedata.getFrom(),calculatedata.getTo(),
						  calculatedata.getAllowance(),calculatedata.getConsumeAllowance());
				    LeaveManager1 lm=new LeaveManager1();
				    lm.updateForApprove(userid,
				    		            day,
				    		            type);
				} catch (DAOSystemException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
		else if(status.equalsIgnoreCase("Approve") &&
				type.equalsIgnoreCase("Compensation Leave"))
		{
			LeaveManager1 lm=new LeaveManager1();
			CompensationLeaveManager1 cm=new CompensationLeaveManager1();
			CompensationLeaveDTO comDTO=cm.findCompensationLeave(userid);
			double balance=comDTO.getBalanceOT();
			double total=comDTO.getTotalOT();
			double consume=comDTO.getConsumeOT();
			
			int day=calculateDifference(from,to);
			double mul=day*8;
			
			double total1=mul+consume;
			
			cm.updateForApproval(comDTO.getId(),total1);
			lm.updateLeaveForApprove(comDTO.getId());
		}
		else if(status.equals("Reject"))
		{
			LeaveManager1 lm=new LeaveManager1();
			lm.updateLeaveForReject(userid);
		}

		RequestDispatcher rd = request.getRequestDispatcher("/process");
		rd.forward(request, response);

	}
	

	private int calculateDifference(Date from,Date to)
	{
		int result;
		result=(int)(to.getTime() - from.getTime()) / (1000 * 60 * 60 * 24);
		return result;
	}
	
	private double calculate(Date from,Date to,double allowance,double consumeallow) throws DAOSystemException
	{
		double result=0.0;
		HolidayCalendarManager hcm=new HolidayCalendarManager();
		ArrayList<HolidayCalendarDTO> holidayDTO=hcm.findAllHolidayCalendar();
		 
		 int holday=getHolidayNumber(from,to,holidayDTO);
		 int offday=(int)(to.getTime() - from.getTime()) / (1000 * 60 * 60 * 24);
		 int connew=offday-holday;
		 result=connew+consumeallow;
		 
		return result;
	}
	
	
	
	private int getHolidayNumber(Date f,Date t,ArrayList<HolidayCalendarDTO> holiday)
	{
		int i=0;
		Calendar fromcal=Calendar.getInstance();
		 fromcal.setTime(f);
		 fromcal.add(Calendar.DATE,1);
		
		 
		   
		   for(HolidayCalendarDTO hol : holiday)
		   {		  
			   while(fromcal.after(f.getDate()-1)&&fromcal.before(t.getDate()+1))
			   {
				   if(fromcal.getTime().equals(hol.getDate()))
				   {
					   i++;
				   }
				   fromcal.add(Calendar.DATE,1);
			   }
		   }
		   
		   return i;
	}
	private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException {
		UserManager1 um = new UserManager1();		
		DetailDTO data = um.findAppliedUser(request.getParameter("id"));        
		request.setAttribute("app", data);
		RequestDispatcher rd = request.getRequestDispatcher("detailview.jsp");
		try {
			rd.forward(request, response);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
